package com.das.mechanic_base.mvp.presenter.create;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.text.TextUtils;

import com.das.mechanic_base.base.X3BaseCallModel;
import com.das.mechanic_base.base.X3BasePresenter;
import com.das.mechanic_base.bean.alone.AloneImageAndRecordBean;
import com.das.mechanic_base.bean.alone.AloneNewBean;
import com.das.mechanic_base.bean.alone.TestRecommendBean;
import com.das.mechanic_base.bean.common.AwsFileBean;
import com.das.mechanic_base.bean.greendao.AloneServiceListBean;
import com.das.mechanic_base.bean.greendao.AloneServiceNewBean;
import com.das.mechanic_base.bean.main.DetectionNewBean;
import com.das.mechanic_base.def.alone.AloneUploadStatus;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.mvp.contract.create.X3AloneSignContract;
import com.das.mechanic_base.mvp.view.create.X3ServiceSignActivity;
import com.das.mechanic_base.utils.X3AloneLayoutUtils;
import com.das.mechanic_base.utils.X3FileUtils;
import com.das.mechanic_base.utils.X3StringUtils;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


/**
 * Created by chenSi on 2018/3/13.
 */

public class X3AloneSignPresenter extends X3BasePresenter<X3AloneSignContract.View> implements X3AloneSignContract.Presenter{

    @Override
    public void uploadImageAws(File imgFile) {
        if (!imgFile.exists()) {
            return;
        }

        if (mView.getContext() == null) {
            return;
        }
        X3ServiceSignActivity context = (X3ServiceSignActivity) mView.getContext();
        if (context.isFinishing()) {
            return;
        }

        if (imgFile.getPath().endsWith(".mp4") || imgFile.getPath().endsWith(".mov")) {
//            uploadNewFile(imgFile,X3FileUtils.getFileLastModifiedTime(imgFile),titleIndex,imgFile.getPath());
        }else {
            try {
                Luban.with(mView.getContext())
                        .load(imgFile.getPath())
                        .ignoreBy(100)
                        .setTargetDir(X3FileUtils.getStoragePath(mView.getContext(), X3FileUtils.MECHANIC_PHOTO_STORAGE_PATH))
                        .filter(path -> !(TextUtils.isEmpty(imgFile.getPath()) || imgFile.getPath().toLowerCase().endsWith(".gif")))
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                            }

                            @Override
                            public void onSuccess(File file) {
                                uploadNewFile(file,X3FileUtils.getFileLastModifiedTime(imgFile));
                            }

                            @Override
                            public void onError(Throwable e) {
                            }
                        }).launch();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private void uploadNewFile(File imgFile,String fileTime) {
        Map<String,Object> imageMap = new HashMap<>();
        imageMap.put("createTime", fileTime);
        imageMap.put("platform", Build.BRAND + " " + Build.MODEL);

        RequestBody requestBody;
        if (imgFile.getPath().endsWith(".mp4") || imgFile.getPath().endsWith(".mov")) {
            requestBody = RequestBody.create(MediaType.parse("video/*"), imgFile);

            MediaMetadataRetriever retr = new MediaMetadataRetriever();
            retr.setDataSource(imgFile.getPath());
            String height = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT); // 视频高度
            String width = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);

            imageMap.put("width",width + "");
            imageMap.put("height",height + "");


        }else {
            requestBody = RequestBody.create(MediaType.parse("image/*"), imgFile);

            Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getPath());

            if (bitmap != null) {
                imageMap.put("width",bitmap.getWidth() + "");
                imageMap.put("height",bitmap.getHeight() + "");
                bitmap.recycle();
            } else {
                try {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(imgFile.getPath(), options);
                    options.inSampleSize = 1;
                    options.inJustDecodeBounds = false;
                    int w = options.outWidth;
                    int h = options.outHeight;
                    imageMap.put("width", w + "");
                    imageMap.put("height", h + "");
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        try {
            String filename = URLEncoder.encode(imgFile.getName(), "UTF-8");

            MultipartBody.Part fileBody = MultipartBody.Part.createFormData("multipartFile", filename, requestBody);

            Map<String,RequestBody> map = new HashMap<>();

            map.put("description",RequestBody.create(MediaType.parse("multipart/form-data"), "签名图片"));

            map.put("ossBucketName",RequestBody.create(MediaType.parse("multipart/form-data"), "SERVICE_PIC"));


            NetWorkHttp.getApi().uploadFileAws(map,fileBody,imageMap)
                    .compose(RxSchedulersHelper.defaultComposeRequest())
                    .compose(mView.bindToLife())
                    .subscribe(new HttpCallBack<AwsFileBean>() {
                        @Override
                        protected void onDone(AwsFileBean awsFileBean) {
                            if (awsFileBean != null){
                                mView.upLoadSuccess(awsFileBean.id);
                            }
                        }

                        @Override
                        protected String LoadingMessage() {
                            return null;
                        }

                        @Override
                        protected void showError(String error) {
                            mView.upLoadFail();
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void saveDetectionFirstInfo(List<DetectionNewBean> mList, long receiveId) {
        NetWorkHttp.getApi().saveDetectionFirstInfo(mList,receiveId)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<Object>() {
                    @Override
                    protected void onDone(Object o) {
                        mView.upUpdateSuccess();
                    }

                    @Override
                    protected void showError(String error) {
                        mView.upUpdateFail("");
                    }
                });
    }

}
